package com.quanshu.shop.order.view;


import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.quanshu.exchange.R;
import com.quanshu.exchange.support.api.ShopInterface;
import com.quanshu.exchange.support.entity.MyOrderEntity;
import com.quanshu.exchange.support.net.BaseResponse;
import com.quanshu.exchange.support.net.core.BaseObserver;
import com.quanshu.exchange.support.net.core.BaseTransformer;
import com.quanshu.exchange.support.net.core.NetClient;
import com.quanshu.exchange.support.utils.AppUtils;
import com.quanshu.exchange.support.utils.LogUtil;
import com.quanshu.exchange.ui.base.BaseActivity;
import com.quanshu.exchange.ui.base.MyApplication;
import com.quanshu.exchange.ui.gui.profile.AllOrderActivity;
import com.quanshu.exchange.ui.gui.profile.order_fragment.DialogDeleteOrder;
import com.quanshu.exchange.ui.gui.profile.order_fragment.RefundDetailActivity;
import com.quanshu.exchange.ui.gui.profile.order_fragment.RefundReasonActivity;
import com.quanshu.shop.base.tool.BaseTool;
import com.quanshu.shop.order.adapter.OrderListAdapter;
import com.trello.rxlifecycle2.components.support.RxFragment;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link OrderList5Fragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class OrderList5Fragment extends RxFragment implements DialogDeleteOrder.DeleteOrderListener {


    @BindView(R.id.my_order_null)
    LinearLayout myOrderNull;
    @BindView(R.id.rl)
    RecyclerView rl;
    Unbinder unbinder;
    private List<MyOrderEntity> myOrderEntityList;
    private OrderListAdapter orderListAdapter;
    private DialogDeleteOrder dialogDeleteOrder;

    public OrderList5Fragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @return A new instance of fragment OrderList5Fragment.
     */
    // TODO: Rename and change types and number of parameters
    public static OrderList5Fragment newInstance() {
        OrderList5Fragment fragment = new OrderList5Fragment();
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onResume() {
        super.onResume();
        getOrderList();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_order_list5, container, false);
        unbinder = ButterKnife.bind(this, view);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        rl.setLayoutManager(linearLayoutManager);
        getOrderList();
        return view;
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            getOrderList();
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }


    //已完成订单
    private void getOrderList() {
        NetClient.getInstance().getShopService(ShopInterface.class)
                .getOrderList(AppUtils.getSignParams(String.valueOf(MyApplication.getInstance().getCurrentUser().getId())),
                        String.valueOf(MyApplication.getInstance().getCurrentUser().getId()), 5)
                .compose(new BaseTransformer<>((BaseActivity) getActivity()))
                .subscribe(new BaseObserver<BaseResponse<List<MyOrderEntity>>>() {
                    @Override
                    public void onSuccess(BaseResponse<List<MyOrderEntity>> response) {
                        myOrderEntityList = response.getData();
                        if (orderListAdapter != null) {
                            orderListAdapter.setNewData(response.getData());
                            Log.d("订单", "onSuccess: 更新全部订单数据" + response.getData().size());
                        } else {
                            orderListAdapter = new OrderListAdapter(myOrderEntityList, getActivity());
                            orderListAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
                                @Override
                                public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                                    switch (view.getId()) {
                                        case R.id.txt_cancel_order://取消订单
                                            doCancelOrder(position);
                                            break;
                                        case R.id.txt_pay_order://去支付
                                            break;
                                        case R.id.txt_apply_order://申请退款
                                            Intent intent = new Intent(getActivity(), RefundReasonActivity.class);
                                            intent.putExtra("orderId", myOrderEntityList.get(position).getOrder_no());
                                            startActivityForResult(intent, 0x01);
                                            break;
                                        case R.id.txt_ok_order://确认收货
                                            doConfirmOrder(position);
                                            break;
                                        case R.id.txt_delete_order://删除订单
                                            showDoDeleteOrder(position);
                                            break;
                                        case R.id.txt_refund_order://退款详情
                                            Intent intent1 = new Intent(getActivity(), RefundDetailActivity.class);
                                            intent1.putExtra("orderId", myOrderEntityList.get(position).getId());
                                            startActivityForResult(intent1, 0x01);
                                            break;
                                        case R.id.root_cl://订单详情
                                            switch (myOrderEntityList.get(position).getIs_inn()) {
                                                case "0"://普通商品
                                                    Bundle bundle = new Bundle();
                                                    bundle.putString(AllOrderActivity.ORDER_ID, myOrderEntityList.get(position).getId());
                                                    BaseTool.goActivity(getActivity(), OrderDetailsActivity.class, bundle);
                                                    break;
                                                case "1"://农产品
                                                    break;
                                                case "3"://活动专区商品
                                                    Bundle bundle2 = new Bundle();
                                                    bundle2.putString(AllOrderActivity.ORDER_ID, myOrderEntityList.get(position).getId());
                                                    BaseTool.goActivity(getActivity(), OrderDetailsActivity.class, bundle2);
                                                    break;
                                                case "4"://秒杀
                                                    break;
                                                case "5"://限购
                                                    break;
                                            }
                                            break;
                                    }
                                }
                            });
                            rl.setAdapter(orderListAdapter);
                        }
                        if (myOrderEntityList != null && myOrderEntityList.size() > 0) {
                            myOrderNull.setVisibility(View.GONE);
                        } else {
                            myOrderNull.setVisibility(View.VISIBLE);
                        }
                    }

                    @Override
                    public void onFailure(Throwable e) {
                        super.onFailure(e);
                    }
                });
    }


    //取消订单
    private void doCancelOrder(int position) {

        NetClient.getInstance().getShopService(ShopInterface.class)
                .doCancelOrder(AppUtils.getSignParams(myOrderEntityList.get(position).getId(), "cancel")
                        , myOrderEntityList.get(position).getId(), "cancel", myOrderEntityList.get(position).getGoods_type())
                .compose(new BaseTransformer<>((BaseActivity) getActivity()))
                .subscribe(new BaseObserver<BaseResponse>() {
                    @Override
                    public void onSuccess(BaseResponse response) {

                        getOrderList();
                    }

                    @Override
                    public void onFailure(Throwable e) {
                        LogUtil.printException(e);
                    }
                });

    }

    //确认收货
    private void doConfirmOrder(int position) {
        NetClient.getInstance().getShopService(ShopInterface.class)
                .doConfirmOrder("", myOrderEntityList.get(position).getId(), "confirm", myOrderEntityList.get(position).getGoods_type())
                .compose(new BaseTransformer<>((BaseActivity) getActivity()))
                .subscribe(new BaseObserver<BaseResponse>() {
                    @Override
                    public void onSuccess(BaseResponse response) {
                        getOrderList();
                    }

                    @Override
                    public void onFailure(Throwable e) {
                        LogUtil.printException(e);
                    }
                });
    }

    //删除订单
    private void showDoDeleteOrder(int position) {
        if (dialogDeleteOrder == null) {
            dialogDeleteOrder = new DialogDeleteOrder(getActivity(), this);
        }
        dialogDeleteOrder.show(position);
    }

    private void deleteOrder(int position) {
        NetClient.getInstance().getShopService(ShopInterface.class)
                .doDeleteOrder(AppUtils.getSignParams(myOrderEntityList.get(position).getId(), "delete"), myOrderEntityList.get(position).getId(), "delete", myOrderEntityList.get(position).getGoods_type())
                .compose(new BaseTransformer<>((BaseActivity) getActivity(), true, false))
                .subscribe(new BaseObserver<BaseResponse>() {
                    @Override
                    public void onSuccess(BaseResponse response) {
                        getOrderList();
                    }

                    @Override
                    public void onFailure(Throwable e) {
                        LogUtil.printException(e);
                    }
                });
    }

    @Override
    public void delete(int p) {
        deleteOrder(p);
    }
}
